
$(function() {

	var space = $(".main-panel");
	var datalist = space.find("table.data-list");
	var api = datalist.xtable("api");

	// 新增地址-打开对话框
	space.find(".btn-toolbar .do-create").click(function() {
		var dialog = $(".modal.edit");
		dialog.modal("show");
		dialog.find(".show-in-update").hide();
		dialog.find(".show-in-create").show();

		var form = dialog.find("form");
		form.attr("action", form.attr("data-create-action"));
		form.clearForm();
	});
	
	// 修改地址-打开对话框
	datalist.on("click", ".do-update", function(e) {
		var btn = $(this);
		var data = api.row(btn.closest("tr")).data();

		var dialog = $(".modal.edit");
		dialog.modal("show");
		dialog.find(".show-in-create").hide();
		dialog.find(".show-in-update").show();

		var areaText = data.areaText || "";
		if (data.township) { areaText += " " + data.township; }
		var form = dialog.find("form");
		form.attr("action", form.attr("data-update-action"));
		form.clearForm();
		form.fillForm($.extend({}, data, { areaText:areaText }));
		return false;
	});
	
	// 删除地址-打开对话框
	datalist.on("click", ".do-delete", function(e) {
		var btn = $(this);
		var data = api.row(btn.closest("tr")).data();

		var dialog = $(".modal.delete");
		dialog.modal("show");
		dialog.find(".show-in-multi").hide();
		dialog.find(".show-in-single").show();

		var form = dialog.find("form");
		form.fillForm("ids", [data.id]);
		return false;
	});

	// 多选删除-打开对话框
	space.find(".btn-toolbar .do-delete").click(function() {
		var btn = $(this);
		var checked = datalist.find("input[name=id]:checkbox:checked");
		if (checked.length == 0) {
			btn.msger("请勾选待删除的记录!")
			return;
		}
		var ids = [];
		checked.each(function() {
			ids.push(this.value);
		});

		var dialog = $(".modal.delete");
		dialog.modal("show");
		dialog.find(".show-in-single").hide();
		dialog.find(".show-in-multi").show().find(".records").text(ids.length);

		var form = dialog.find("form");
		form.fillForm("ids", ids);
	});

	// 设为默认地址
	datalist.on("click", ".do-default", function(e) {
		var btn = $(this);
		var data = api.row(btn.closest("tr")).data();

		var url = btn.zoptions().url || btn.attr("data-url");
		btn.zajax(url, { id:data.id }, function() {
			api.reload();
		});
		return false;
	});

	// 提交表单
	$(".modal.edit, .modal.delete").find(".do-submit").click(function() {
		var btn = $(this);
		var dialog = btn.closest(".modal");
		var form = dialog.find("form");
		btn.zajax(form, function() {
			dialog.modal("hide");
			api.reload();
		});
	});

	// 初始化地址选择控件
	$(".modal.edit").on("show.bs.modal", function() {
		var me = $(this);
		if (me.data("AreaDivisionInit")) { return; }
		me.data("AreaDivisionInit", true);
		me.find(".area-division-box").areaChoose({
			fixedParams: { sceneType:"default" }
		});
	});
});

+function($) {
	$.fn.xtable.render.add("areaText", {
		render: function(value, type, data, meta) {
			var areaText = value || "";
			if (data.township) { areaText += " " + data.township; }
			return areaText;
		}
	});
}(window.jQuery);
